﻿using System.IO;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;

namespace AbpOne.EntityFrameworkCore.DbMigrations.EntityFrameworkCore {
    /// <summary>
    /// Design Time Db Factory
    /// 主要是用来使用Code-First命令的(Add-Migration 和 Update-Database)
    /// 关于dotnet cli的efcore操作参考：https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet
    /// </summary>
    public class AbpOneMigrationsDbContextFactory : IDesignTimeDbContextFactory<AbpOneMigrationsDbContext> {
        public AbpOneMigrationsDbContext CreateDbContext(string[] args) {
            var configuration = BuildConfiguration();

            // 读取配置文件里的链接字符串
            var builder = new DbContextOptionsBuilder<AbpOneMigrationsDbContext>()
                .UseSqlite(configuration.GetConnectionString("Sqlite"));

            return new AbpOneMigrationsDbContext(builder.Options);
        }

        private static IConfigurationRoot BuildConfiguration() {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            return builder.Build();
        }
    }
}